package com.example.day17_servicetest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private MyService.DownloadBinder downloadBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (MyService.DownloadBinder) service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button_start = findViewById(R.id.start);
        Button button_stop = findViewById(R.id.stop);
        button_start.setOnClickListener(this);
        button_stop.setOnClickListener(this);

        Button button_bind = findViewById(R.id.bind_service);
        Button button_unbind = findViewById(R.id.unbind_service);
        button_bind.setOnClickListener(this);
        button_unbind.setOnClickListener(this);

        Button button_IntentService = findViewById(R.id.intent_service);
        button_IntentService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                Intent intent_start = new Intent(this, MyService.class);
                startService(intent_start);
                break;
            case R.id.stop:
                Intent intent_stop = new Intent(this, MyService.class);
                stopService(intent_stop);
                break;
            case R.id.bind_service:
                Intent intent_bind = new Intent(this, MyService.class);
                bindService(intent_bind, connection, BIND_AUTO_CREATE); // 绑定服务
                break;
            case R.id.unbind_service:
                unbindService(connection);  // 解绑服务
                break;
            case R.id.intent_service:
                Log.d("MainActivity", "主线程id是 "+Thread.currentThread().getId());
                Intent intentService = new Intent(this, MyIntentService.class);
                startService(intentService);
                break;
            default:
                break;
        }
    }
}
